<template>
	<view class="wrapper">
		<view class="title">当日累计预警数</view>
		<view class="statistics">
			<view class="statistics-list">
				<view class="statistics-list-title">行为预警</view>
				<view class="statistics-list-number">{{ dayData.behavior }}</view>
			</view>
			
			<view class="statistics-list">
				<view class="statistics-list-title">触网预警</view>
				<view class="statistics-list-number">{{ dayData.touchNet }}</view>
			</view>

			<view class="statistics-list">
				<view class="statistics-list-title bold">共</view>
				<view class="statistics-list-number">
					{{ Number(dayData.touchNet) + Number(dayData.behavior) }}
				</view>
			</view>
		</view>

		<view class="title">当月累计预警数</view>
		<view class="statistics">
			<view class="statistics-list">
				<view class="statistics-list-title">行为预警</view>
				<view class="statistics-list-number">{{ monthData.behavior }}</view>
			</view>
			
			<view class="statistics-list">
				<view class="statistics-list-title">触网预警</view>
				<view class="statistics-list-number">{{ monthData.touchNet }}</view>
			</view>

			<view class="statistics-list">
				<view class="statistics-list-title bold">共</view>
				<view class="statistics-list-number">
					{{ Number(monthData.touchNet) + Number(monthData.behavior) }}
				</view>
			</view>
		</view>

		<div class="space"></div>

		<view class="uni-segmented-control-wrapper">
			<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" styleType="button"
				activeColor="#4BB7DB" inActiveColor="#F6F8FE"></uni-segmented-control>
			<view class="content" style="padding: 15rpx">
				<view v-show="current === 0">
					<Behavior />
				</view>
				<view v-show="current === 1">
					<Online />
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from "vue";
	import {
		onShow
	} from "@dcloudio/uni-app";
	import {
		onBackPress
	} from "@dcloudio/uni-app";
	import {
		HOST
	} from "../../static/js/const";
	import Online from "./online.vue";
	import Behavior from "./behavior.vue";

	// 拦截系统返回键
	onBackPress(() => {
		// 返回 true 表示阻止默认返回行为
		return true;
	});

	const items = ref(["行为预警", "触网预警"]);
	const current = ref(0);
	let monthData = ref({
		touchNet: 0,
		behavior: 0,
	});

	let dayData = ref({
		touchNet: 0,
		behavior: 0,
	});

	function onClickItem(e) {
		if (current.value !== e.currentIndex) {
			current.value = e.currentIndex;
		}
	}
	
	// 获取当日零点时间（本地时区）
	const getTodayZeroTime = () => {
	    const now = new Date();
	    now.setHours(0, 0, 0, 0); // 设置为 00:00:00
	    return now;
	};
	
	// 获取当月第一天零时
	const getFirstDayZeroTime = () => {
	    const now = new Date();
	    return new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0);
	};
	
	// 格式化日期为 YYYY-MM-DD hh:mm:ss
	const formatDate = (date) => {
	    const year = date.getFullYear();
	    const month = String(date.getMonth() + 1).padStart(2, '0');
	    const day = String(date.getDate()).padStart(2, '0');
	    const hours = String(date.getHours()).padStart(2, '0');
	    const minutes = String(date.getMinutes()).padStart(2, '0');
	    const seconds = String(date.getSeconds()).padStart(2, '0');
	    
	    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	};
	
	// 获取当前时间（本地时区）
	function getCurrentFormattedTime() {
	    const now = new Date();
	    // 获取时间分量
	    const year = now.getFullYear();
	    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零（0-11 → 1-12）[1,4](@ref)
	    const day = String(now.getDate()).padStart(2, '0');         // 日期补零
	    const hours = String(now.getHours()).padStart(2, '0');      // 小时补零
	    const minutes = String(now.getMinutes()).padStart(2, '0'); // 分钟补零
	    const seconds = String(now.getSeconds()).padStart(2, '0');  // 秒数补零
	    
	    // 拼接为标准格式
	    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}
	
	const zeroTime = getTodayZeroTime();
	const firstDayZero = getFirstDayZeroTime();
	const currentFormattedTime = getCurrentFormattedTime();
	console.log("当前时间"); 
	console.log(formatDate(zeroTime)); // 输出如 "2025-06-05 00:00:00"
	console.log(formatDate(firstDayZero)); // 输出：2025-06-01 00:00:00
	console.log(currentFormattedTime); // 输出：2025-06-01 00:00:00

	onShow(() => {
		// 当月
		uni.request({
			url: `${HOST}/alarm/alarmInfo/pageSearch`,
			method: "POST",
			header: {
				"content-type": "application/json",
				Authorization: "Bearer " + uni.getStorageSync("accessToken"),
			},
			data: {
			  current: 1,
			  data: {
				alarmDatetimeStart: formatDate(firstDayZero),
			    alarmDatetimeEnd: currentFormattedTime,
			    alarmType: "2",
			    // warningStatus: "0"
			  },
			  size: 10000000000
			},
			success: (res) => {
				if (res.data.status === "OK" && res.data.flag) {
					console.log("当月：");
					console.log(res);
					monthData.value.behavior = res.data.data.total;
				} else if (Number(res.data.code) === 401) {
					uni.showToast({
						title: "登录超时",
						icon: "error",
					});
					uni.removeStorageSync("accessToken");
					uni.reLaunch({
						url: "/pages/login/index", // 这里的URL是登录页面的路径
					});
				} else {
					uni.showToast({
						title: res.data.message,
						icon: "error",
					});
				}
			},
			fail: (err) => {
				console.error("请求失败", err);
				uni.showToast({
					title: "连接失败",
					icon: "error",
				});
			},
		});
		
		uni.request({
			url: `${HOST}/alarm/alarmInfo/pageSearch`,
			method: "POST",
			header: {
				"content-type": "application/json",
				Authorization: "Bearer " + uni.getStorageSync("accessToken"),
			},
			data: {
			  current: 1,
			  data: {
				alarmDatetimeStart: formatDate(firstDayZero),
			    alarmDatetimeEnd: currentFormattedTime,
			    alarmType: "1",
			    // warningStatus: "0"
			  },
			  size: 10000000000
			},
			success: (res) => {
				if (res.data.status === "OK" && res.data.flag) {
					console.log("当月：");
					console.log(res);
					monthData.value.touchNet = res.data.data.total;
				} else if (Number(res.data.code) === 401) {
					uni.showToast({
						title: "登录超时",
						icon: "error",
					});
					uni.removeStorageSync("accessToken");
					uni.reLaunch({
						url: "/pages/login/index", // 这里的URL是登录页面的路径
					});
				} else {
					uni.showToast({
						title: res.data.message,
						icon: "error",
					});
				}
			},
			fail: (err) => {
				console.error("请求失败", err);
				uni.showToast({
					title: "连接失败",
					icon: "error",
				});
			},
		});

		// 当日
		uni.request({
			url: `${HOST}/alarm/alarmInfo/pageSearch`,
			method: "POST",
			header: {
				"content-type": "application/json",
				Authorization: "Bearer " + uni.getStorageSync("accessToken"),
			},
			data: {
			  current: 1,
			  data: {
				alarmDatetimeStart: formatDate(zeroTime),
			    alarmDatetimeEnd: currentFormattedTime,
			    alarmType: "2",
			    // warningStatus: "0"
			  },
			  size: 10000000000
			},
			success: (res) => {
				if (res.data.status === "OK" && res.data.flag) {
					console.log("当日：");
					console.log(res);
					dayData.value.behavior = res.data.data.total;
				} else if (Number(res.data.code) === 401) {
					uni.showToast({
						title: "登录超时",
						icon: "error",
					});
					uni.removeStorageSync("accessToken");
					uni.reLaunch({
						url: "/pages/login/index", // 这里的URL是登录页面的路径
					});
				} else {
					uni.showToast({
						title: res.data.message,
						icon: "error",
					});
				}
			},
			fail: (err) => {
				console.error("请求失败", err);
				uni.showToast({
					title: "连接失败",
					icon: "error",
				});
			},
		});
		
		uni.request({
			url: `${HOST}/alarm/alarmInfo/pageSearch`,
			method: "POST",
			header: {
				"content-type": "application/json",
				Authorization: "Bearer " + uni.getStorageSync("accessToken"),
			},
			data: {
			  current: 1,
			  data: {
				alarmDatetimeStart: formatDate(zeroTime),
			    alarmDatetimeEnd: currentFormattedTime,
			    alarmType: "1",
			    // warningStatus: "0"
			  },
			  size: 10000000000
			},
			success: (res) => {
				if (res.data.status === "OK" && res.data.flag) {
					console.log("当日：");
					console.log(res);
					dayData.value.touchNet = res.data.data.total;
				} else if (Number(res.data.code) === 401) {
					uni.showToast({
						title: "登录超时",
						icon: "error",
					});
					uni.removeStorageSync("accessToken");
					uni.reLaunch({
						url: "/pages/login/index", // 这里的URL是登录页面的路径
					});
				} else {
					uni.showToast({
						title: res.data.message,
						icon: "error",
					});
				}
			},
			fail: (err) => {
				console.error("请求失败", err);
				uni.showToast({
					title: "连接失败",
					icon: "error",
				});
			},
		});
	});
</script>

<style lang="scss" scoped>
	.wrapper::v-deep .uni-section-header {
		display: none !important;
	}

	.wrapper::v-deep .uni-section {
		max-height: calc(100vh - 820rpx);
		overflow: auto;
	}

	.wrapper::v-deep .uni-segmented-control-wrapper {
		border-radius: 10rpx;
		padding: 15rpx 0;

		.content {
			height: auto;
			overflow: auto;
			padding-top: 0 !important;
		}
	}
</style>